package com.py.credit.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.CreditReportLog;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.CreditHistoryEnmu;
import com.py.credit.service.CreditReportService;
import com.py.credit.service.GetRoleService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.FileUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping(value = "/creditCheck")
public class CreditCheckHistoryController {

	private final static String FRONT_TABLE_CREDIT_REPORT_ID = "creditReport";

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Value("${absolutepath}")
	private String absolutepath;
	@Autowired
    private GetRoleService getRoleService;
	@Autowired
	private CreditReportService creditReportService;

	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums(
			@RequestParam(value = "kId", defaultValue = "100000", required = true) String kId) {

		return new RestServiceResult<List<OptionalColumn>>(CreditHistoryEnmu.getOptionalColumns(kId));

	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns(
			@RequestParam(value = "kId", defaultValue = "100000", required = true) String kId) {

		return new RestServiceResult<List<OptionalColumn>>(CreditHistoryEnmu.getAdvancedConditionColumns(kId));

	}

	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<List<Map<String, Object>>> getTableList(
			@RequestParam(value = "kId", defaultValue = "100000", required = true) String kId,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		String[] configColumns = null;
		 String rolename="";
		 String username=null;
		 String deptname=null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {

				//获取当前用户所属部门
				deptname=	userInfo.getOfficeName();
				//获取当前用户ID
				username = userInfo.getUsername();
				//获取用户角色信息
				List<HashMap<String,Object>> rolenames =  getRoleService.getRolesByUserId(userInfo.getId(), HttpServletHelper.getUserToken(request)).getData();   
		        for (Map<String, Object> map : rolenames) {         	
		            for (String key : map.keySet()) {
		           	 if(key.equals("roleName")) {
		           		 if(map.get(key)!=null) {
		           			 rolename = (String) map.get(key);
		           		 }
		           		 break;
		           	 }
		            }
		        }

				configColumns = (String[]) MapCache
						.get(userInfo.getId() + "_" + FRONT_TABLE_CREDIT_REPORT_ID + "_" + kId);
			} else {

				ExceptionLogger.error("CreditCheckHistoryController#getTableList", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("CreditCheckHistoryController#getTableList", "未获取到当前用户信息！");
		}

		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? CreditHistoryEnmu.getDefaultShowColumnEN(kId) : Arrays.asList(configColumns);

		String[] additionalColumns = { "ID", "ENTITY_TYBM", "LOCATION", "ENTITY_K_ID" };
		List<Map<String, Object>> tableList =  null;
		if(rolename.equals("系统管理员")) {
			tableList =	creditReportService.getByConditionForPage(kId, showColumns,
					additionalColumns, condition, page,null,null);
		}else if(rolename.equals("部门管理员")) {
			tableList =	creditReportService.getByConditionForPage(kId, showColumns,
					additionalColumns, condition, page,username,null);
		}else {
			tableList =	creditReportService.getByConditionForPage(kId, showColumns,
					additionalColumns, condition, page,username,deptname);
		}
		

		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), tableList);

	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			@RequestParam(value = "kId", defaultValue = "100000", required = true) String kId,
			HttpServletRequest request) {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {

				MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_CREDIT_REPORT_ID + "_" + kId, columns);
			} else {

				ExceptionLogger.error("CreditCheckHistoryController#addShowColunms", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("CreditCheckHistoryController#addShowColunms", "未获取到当前用户信息！");
		}

		return new RestServiceResult<String>();
	}

	@RequestMapping(value = "/exportList.json")
	public void exportCommoncontentList(
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
			@RequestParam(value = "kId", defaultValue = "100000", required = true) String kId,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletResponse response) throws IOException {

		page.setLimit(1000);

		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		List<Map<String, Object>> tableList = creditReportService.getByConditionForPage(kId, showColumns, null,
				condition, page,null,null);

		List<OptionalColumn> optionalColumns = CreditHistoryEnmu.getOptionalColumns(kId);

		ExcelUtil.downloadExcel(response, tableList, "信用核查历史列表", "信用核查历史列表", showColumns, optionalColumns);

	}

	@RequestMapping(value = "/reportDownLod.json")
	public void downlodReport(@RequestParam(value = "location", defaultValue = "", required = true) String location,
			@RequestParam(value = "id", defaultValue = "", required = true) int id, HttpServletResponse response,
			HttpServletRequest request) {

		if (StringUtils.isBlank(location) || !(new File(absolutepath + location).exists())) {

			throw new ServiceException("报告已不存在,请重新生成");

		}

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {

				String deptName = userInfo.getOfficeName();
				String realName = userInfo.getRealName();
				String userName = userInfo.getUsername();
				CreditReportLog log = new CreditReportLog(null, id, new Date(), userName, realName, deptName);
				creditReportService.addReportLog(log);

			} else {

				ExceptionLogger.error("CreditCheckHistoryController#addShowColunms", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("CreditCheckHistoryController#addShowColunms", "未获取到当前用户信息！");
		}

		FileUtil.downloadFile(absolutepath + location, response);

	}

	@RequestMapping(value = "/reportPreview.json")
	public void reportPreview(@RequestParam(value = "location", defaultValue = "", required = true) String location,
			HttpServletResponse response) throws IOException {

		if (StringUtils.isBlank(location) || !(new File(absolutepath + location).exists())) {

			throw new ServiceException("报告已不存在,请重新生成");

		}

		response.setContentType("application/pdf");

		ServletOutputStream outputStream = response.getOutputStream();

		response.setHeader("Content-Disposition", "inline;fileName=Credit_Report.pdf");

		File pdf = null;
		FileInputStream fis = null;
		byte[] buffer = new byte[1024 * 1024];
		pdf = new File(absolutepath + location);
		response.setContentLength((int) pdf.length());
		fis = new FileInputStream(pdf);
		int readBytes = -1;
		while ((readBytes = fis.read(buffer, 0, 1024 * 1024)) != -1) {
			outputStream.write(buffer, 0, 1024 * 1024);
		}
		outputStream.close();
		fis.close();

	}

	@RequestMapping(value = "/getReportTrace.json")
	public RestServiceResult<List<Map<String, Object>>> getReportLog(
			@RequestParam(value = "reportId", defaultValue = "", required = true) int id) {

		List<Map<String, Object>> reportTrace = creditReportService.getReportTrace(id);

		return new RestServiceResult<List<Map<String, Object>>>(reportTrace);

	}

	@RequestMapping(value = "/getReportDetail.json")
	public RestServiceResult<CreditReportLog> getReportDetail(
			@RequestParam(value = "id", defaultValue = "", required = true) int id) {

		CreditReportLog reportLog = creditReportService.getReportLogDetail(id);

		return new RestServiceResult<CreditReportLog>(reportLog);

	}

}
